<template>
  <div class="price-input-view">

    <el-input v-model="price" :placeholder="placeholder" :disabled="disabled" :clearable="clearable" @input="onInput" @blur="onBlur" @focus="onFocus" @clear="priceClear">
      <template v-if="isUnit" #append>{{ unitStr }}</template>
    </el-input>

  </div>
</template>

<script>
import {computed, defineComponent} from 'vue'

export default defineComponent({
  name: 'Index',
  emits:['blur','input','clear','focus'],
  props: {
    data: {
      type: String,
      default: 0
    },
    isUnit: {
      type: Boolean,
      default: false,
    },
    unitStr: {
      type: String,
      default: '元'
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: false,
    }
  },
  setup(props, { emit }) {
    const dealValue = (val) => {
      // this.form.skus[e].Price 是input的值
      // 先把非数字的都替换掉，除了数字和.
      val = val.replace(/[^\d.]/g, '')
      // 必须保证第一个为数字而不是.
      val = val.replace(/^\./g, '')
      // 保证只有出现一个.而没有多个.
      val = val.replace(/\.{2,}/g, '')
      // 保证.只出现一次，而不能出现两次以上
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      let index = -1
      for (const i in val) {
        if (val[i] === '.') {
          index = i
        }
        if (index !== -1) {
          if (i - index > 2) {
            val = val.substring(0, val.length - 1)
          }
        }
      }
      console.log(val)
      return val
    }

    const price = computed({
      get() {
        return props.data
      },
      set(value) {
        const va = dealValue(value)
        emit('update:data', va)
        return props.data
      }
    })

    const onBlur = (val) => {
      emit('blur', price.value)
    }

    const onInput = (val) => {
      emit('input', price.value)
    }

    const priceClear = () => {
      // price.value = val
      emit('clear', price.value)
    }

    const onFocus = () => {
      emit('focus', price.value)
    }

    return {
      price,

      onInput,
      priceClear,
      onBlur,
      onFocus,
    }
  }
})
</script>

<style scoped>

</style>
